﻿using AutoMapper;
using B.S.Material.Domain.BOM;
using B.S.Material.ErrorCode;
using B.S.Material.Read.Api.Applications.Command.MaterialsCommnad;
using MediatR;
using SqlSugar;

namespace B.S.Material.Read.Api.Applications.Handler.MaterialsHandler
{
    public class GetMaterialsHandler : IRequestHandler<GetMaterialsCommnad, ApiResult<ApiPaging<Materials>>>
    {
        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;
        public GetMaterialsHandler(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }
        public async Task<ApiResult<ApiPaging<Materials>>> Handle(GetMaterialsCommnad request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<Materials>> reat = new ApiResult<ApiPaging<Materials>>();
            var listtt = await db.Queryable<Materials>().Where(x => !x.IsDel).ToListAsync();
            if (!string.IsNullOrEmpty(request.BOMSubject))
            {
                listtt = listtt.Where(x => x.BOMSubject.Contains(request.BOMSubject)).ToList();
            }
            if (!string.IsNullOrEmpty(request.DocumentNo))
            {
                listtt = listtt.Where(x => x.DocumentNo.Contains(request.DocumentNo)).ToList();
            }
            if (!string.IsNullOrEmpty(request.ProductName))
            {
                listtt = listtt.Where(x => x.ProductName.Contains(request.ProductName)).ToList();
            }
            if (!string.IsNullOrEmpty(request.Creator))
            {
                listtt = listtt.Where(x => x.Creator.Contains(request.Creator)).ToList();
            }
            if (request.CreationTime != null)
            {
                listtt = listtt.Where(x => x.CreationTime.Date == request.CreationTime.Value.Date).ToList();
            }
            int totalCount = listtt.Count();
            int PageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);
            listtt = listtt.OrderByDescending(a => a.BOMID).Skip((request.pageindex - 1) * request.pageSize).Take(request.pageSize).ToList();
            ApiPaging<Materials> paging = new ApiPaging<Materials>()
            {
                totalCount = totalCount,
                PageCount = PageCount,
                Result = listtt.ToList(),

            };

            reat.Code = ApiEnum.显示成功;
            reat.MAG = ApiEnum.显示成功.ToString();
            reat.data = paging;
            return reat;
        }
    }
}
